﻿using System;
using System.Security.Cryptography;
using System.Text;

namespace YueRu.Common.Encrypt
{
    /// <summary> 
    /// Advanced Encryption Standard高级加密标准
    /// </summary> 
    public static class AES
    {
        //默认密钥向量
        private static readonly byte[] Keys = { 0x41, 0x72, 0x65, 0x79, 0x6F, 0x75, 0x6D, 0x79, 0x53, 0x6E, 0x6F, 0x77, 0x6D, 0x61, 0x6E, 0x3F };

        public static string Encode(string encryptString, string encryptKey)
        {
            encryptKey = StringExtend.GetSubString(encryptKey, 32, "");
            encryptKey = encryptKey.PadRight(32, ' ');

            var rijndaelProvider = new RijndaelManaged
            {
                Key = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 32)),
                IV = Keys
            };
            var rijndaelEncrypt = rijndaelProvider.CreateEncryptor();

            var inputData = Encoding.UTF8.GetBytes(encryptString);
            var encryptedData = rijndaelEncrypt.TransformFinalBlock(inputData, 0, inputData.Length);

            return Convert.ToBase64String(encryptedData);
        }

        public static string Decode(string decryptString, string decryptKey)
        {
            if (decryptString == string.Empty)
            {
                return string.Empty;
            }
            try
            {
                decryptKey = StringExtend.GetSubString(decryptKey, 32, "");
                decryptKey = decryptKey.PadRight(32, ' ');

                var rijndaelProvider = new RijndaelManaged
                {
                    Key = Encoding.UTF8.GetBytes(decryptKey), 
                    IV = Keys
                };
                var rijndaelDecrypt = rijndaelProvider.CreateDecryptor();

                var inputData = Convert.FromBase64String(decryptString);
                var decryptedData = rijndaelDecrypt.TransformFinalBlock(inputData, 0, inputData.Length);

                return Encoding.UTF8.GetString(decryptedData);
            }
            catch
            {
                return "";
            }

        }

    }
}